<template>
  <div class="page bgc-fff">
    <!-- title -->
    <div class="title-wrap pad-l-r42">
      <div class="f26 ta-l c-333 mt50 pad-t5">
        您好，
      </div>
      <div class="f16 ta-l c-999 mt20">
        欢迎使用中联物流运力平台,
        <!-- <br/> -->
        立即<span @click="toRegist" class="c-1E90FF">注册承运商</span>或者
        <span @click="toDirverRegist" class="c-1E90FF">加入承运商</span>
      </div>
    </div>
    <!-- input查询 -->
    <div class='login-input-wrap'>
      <!-- <input type="hidden" name="_csrf" id="order_csrf" value="<?php //echo Yii::$app->request->csrfToken?>"/> -->
      <div class="login-input-box">
        <div class="input-cells a-between">
          <!-- <div class="f-fl input-label">手机号码</div> -->
          <div class="flex l-center a-left">
            <input type="tel" class="pad-l20 cell-input cell-input-phone" placeholder="请输入手机号码"
              maxlength="11" v-model.trim="loginParam.phone" @keyup = "phoneKeyup"/>
          </div>
          <img v-show="loginParam.phone" class="icon-delete"
              :src="staticImgData.imgurla" alt="" @click="cleanInput('phone')">
        </div>
        <div class="input-cells mt10">
          <!-- <div class="f-fl input-label">验证码</div> -->
          <input type="tel" class="pad-l20 cell-input cell-input-vcode"   placeholder="短信验证码"
              style="text-align:left;" maxlength="6"  v-model.trim="loginParam.verify_code"  />
          <div class ="f-fr cell-vcode-btn disabled"  @click="getPhoeCode"
            :class="[{'c-1E90FF':code_prevent}]" > {{code_msg}} </div>
        </div>
      </div>
      <div>
        <p class="large-btn"
          :disabled="disabled && disabled_45s" :class="[{'bgc-7cbdff':!disabled && !disabled_45s}]"
          @click="subAxios">登录</p>
      </div>
      <div class="flex a-right l-center pad15">
        <span class="mr15 f12 c-01a4f6">忘记密码？</span>
        <span class="f12 c-01a4f6" @click="toLoginNormal">使用密码登录</span>
      </div>
      <!-- <div class="flex a-center l-center mt50">
        <span class="line-left"></span>
        <span class="c-B2B2B2 f12" style="line-height:.15rem;">绑定手机即可登录接单</span>
        <span class="line-right"></span>
      </div> -->
    </div>

    <v-loading  v-show="loadingShow" style="z-index:11" ></v-loading>
  </div>
</template>

<script type="text/ecmascript-6">
  import Loading from '@/components/common/loading/loading.vue'
  import { Toast } from 'mint-ui'
  import util from '@/utils/util'
  import { mapGetters } from 'vuex'
  import * as AccountApi from '@/api/account'
  export default {
    name: 'signup-sms',
    data() {
      return {
        nums: 15,
        staticImgData: {
          imgurla: require('@/assets/image/common/icon_delete.png')
        },
        loginParam: {
          phone: '',
          verify_code: '' // /*验证码*/
        },
        clock: '',
        code_msg: '获取验证码',
        seconds: 60, // 倒计时时间
        code_prevent: false, // /*禁止点击按钮*/
        // loadingShow: false, // loading显隐
        disabled: true, // 登录禁止点击
        disabled_45s: true, // 临时控制倒计时45s时放开提交按钮
        loadingFail: false
      }
    },
    components: {
      'v-loading': Loading
    },
    computed: {
      loginParamCom() {
        const { phone, verify_code } = this.loginParam
        return {
          phone,
          verify_code
        }
      },
      ...mapGetters(['loadingShow'])
    },
    watch: {
      loginParamCom: {
        handler: function(newValData) {
          const that = this
          const vala = newValData.phone.length
          const vald = newValData.verify_code.length
          if (vala === 11 && vald === 6) {
            that.disabled = false
          } else {
            that.disabled = true
          }
        },
        deep: true
      }
    },
    created() {

    },
    mounted() {

    },
    methods: {
      cleanInput: function(val) {
        const res_val = val
        if (res_val === 'phone') {
          this.loginParam.phone = ''
        }
      },
      phoneKeyup: function() { // 电话号码输入框
        const key = this.loginParam.phone.length
        if (key === 11) {
          // console.log('key', key)
          // document.activeElement.blur()
          this.code_prevent = true
        } else {
          this.code_prevent = false
          this.telFormatting(this.loginParam.phone)
        }
      },
      telFormatting: function(param) { // 电话号码格式化
        let num = this.loginParam.phone
        let num_ = this.loginParam.phone
        num = num.replace(/\s/g, '').substring(0, 3).replace(/(.{3})/g, '$1')
        num_ = num_.replace(/\s/g, '').substring(3).replace(/(.{4})/g, '$1')
        this.loginParam.phone = num + num_
        this.loginParam.phone = (num + num_).substring(0, 13)
        // console.log('telFormatting-this.loginParam.phone', this.loginParam.phone)
      },
      getPhoeCode: function() {
        const that = this
        const mobile = that.loginParam.phone.replace(/\s/g, '')
        // console.log('点击发送验证码按钮', 'mobile', mobile)
        if (mobile === '') {
          Toast({
            message: '请先填写手机号码'
          })
          return
        }
        const check_res = that.checkMyMobile(mobile)
        // console.log('check_res', check_res)
        that.code_prevent = true
        if (check_res) {
          if (!that.code_prevent) return
          that.code_msg = '发送中…'
          that.code_prevent = true
          // 获取短信验证码
          const formData = new FormData()
          formData.append('phone', mobile)
          AccountApi.getLoginVerifyCode(formData).then(res => {
            // console.log('getLoginVerifyCode()', res)
            if (res.status === 200) {
              if (res.data.code === 0) {
                Toast({
                  message: '验证码发送成功'
                })
                that.code_msg = that.seconds + 's'
                that.clock = setInterval(that.doLoop, 1000) // 一秒执行一次
                setTimeout(() => {
                  that.disabled_45s = false
                }, 15000)
                that.code_prevent = false
              } else if (res.data.code === 22 || res.data.code === 33 || res.data.code === 20) {
                that.code_msg = '获取验证码'
                Toast({
                  message: res.data.msg,
                  duration: 1500
                })
                that.code_prevent = false
                return
              } else if (res.data.code === 3 || res.data.code === 2 || res.data.code === 1 || res.data.code === 4) {
                console.log('res.data.msg', res.data.msg)
                that.code_msg = '获取验证码'
                Toast({
                  message: '系统错误请联系管理员！',
                  duration: 1500
                })
                that.code_prevent = false
                return
              } else {
                that.code_msg = '获取验证码'
                Toast({
                  message: '验证码发送失败'
                })
                that.code_prevent = false
                return
              }
            } else {
              that.code_msg = '获取验证码'
              Toast({
                message: '验证码发送失败'
              })
              that.code_prevent = false
              return
            }
          }).catch(res => {
            that.code_msg = '获取验证码'
            Toast({
              message: '验证码发送失败'
            })
            that.code_prevent = false
          })
        }
      },
      checkMyMobile: function(mobile) {
        const mobile_res = util.checkMobile(mobile)
        if (!mobile_res) {
          Toast({
            message: '请输入有效的联系电话！'
          })
          return
        }
        return true
      },
      doLoop: function() {
        // 倒计时
        const key = this.loginParam.phone.length
        this.seconds--
        if (this.seconds > 0) {
          this.code_msg = this.seconds + 's'
          if (key !== 11) {
            // 在验证码已发到错误手机号倒计时已开始状态中，修改手机号时，重置倒计时，禁用
            clearInterval(this.clock)
            // 清除js定时器
            this.code_state = true
            this.code_msg = '获取验证码'
            this.seconds = 60 // 重置时间
            this.code_prevent = false
          } else if (this.loadingFail) {
            // 在验证码正在倒计时状态中，点击登录后但登录失败（或验证码的提交错误），重置倒计时，可用
            clearInterval(this.clock) // 清除js定时器
            this.code_state = true
            this.code_msg = '获取验证码'
            this.seconds = 60 // 重置时间
            this.code_prevent = true
          }
        } else {
          clearInterval(this.clock) // 清除js定时器
          this.code_state = true
          this.code_msg = '获取验证码'
          this.seconds = 60 // 重置时间
          this.code_prevent = true
        }
      },
      subAxios: function() {
        // 公共验证
        const that = this
        const mobile = that.loginParam.phone.replace(/\s/g, '')
        const verifyCode = that.loginParam.verify_code.replace(/(^\s*)|(\s*$)/g, '')
        // console.log('输入框内的验证码', verifyCode)
        if (mobile === '') {
          Toast({
            message: '请输入手机号码'
          })
          return
        }
        const phone_res = util.checkMobile(mobile)
        if (!phone_res) {
          // msg.tips('请输入有效的手机号码', 'warn')
          Toast({
            message: '请输入有效的手机号码'
          })
          return
        }
        if (!verifyCode) {
          // msg.tips('请输入短信验证码', 'warn')
          Toast({
            message: '请输入短信验证码'
          })
          return
        }
        // const req_params = { authType: 'MobileNumber', accountNo: parseInt(mobile), extra: verifyCode }
        console.log('that.disabled', that.disabled, 'that.disabled_45s', that.disabled_45s)
        if (that.disabled || that.disabled_45s) { return false }
        that.disabled = true
        const toParam = {
          username: mobile,
          verifyCode
        }
        // 要token
        that.$store.dispatch('LoginSms', toParam)
        that.disabled = false
      },
      toRegist: function() {
        this.$router.push({ name: 'company-signup' })
      },
      toDirverRegist: function() {
        this.$router.push({ name: 'driver-signup' })
      },
      toLoginNormal: function() {
        this.$router.push({ name: 'signup-normal' })
      }
    }
  }
</script>

<style scoped>
  @import '../../styles/util.css';
  @import '../../styles/login_regist.css';
  .cell-input.cell-input-phone{
    width: 2.3rem;
    overflow: hidden;
    text-overflow:ellipsis;
    white-space:nowrap;
    text-align:left;
  }
  .input-cells.a-between{
    -webkit-justify-content: space-between;
    -moz-justify-content: space-between;
    -ms-justify-content: space-between;
    -webkit-box-pack: justify;
    justify-content: space-between;
  }
  .input-cells>img{
    display: block;
    width: .32rem;
    height: .32rem;
    margin-right: 0;
    padding-right: 0.08rem;
  }
</style>
